
var newscene = {
	attach:"",
	attachtype:"img",
	thread:0,
	user:"",
	userid:0,
	replyid:0,
	uploadrequest:null,
	commandMenuModel:{
		visible: true,
        items: [ 
            { icon: "attach", command: "do-Attach"},
            { icon: 'send', command: "do-Send"}
        ]
	}
}

var answered=new Array();


function StageAssistant() {
	/* this is the creator function for your stage assistant object */
}

StageAssistant.prototype.setup = function() {
	/* this function is for setup tasks that have to happen when the stage is first created */
	this.controller.pushScene("Main");
}

addAnswered = function(name, thread)
{
	for(i=0;i<answered.length;i++) //ignore dups
		if(answered[i].thread==thread)
			return;
	Mojo.Log.info("Bookmark added:"+name+":"+thread);
	var i=answered.length;
	answered[i]={};
	answered[i].thread=thread;
	answered[i].name=name;
	var a = new Mojo.Model.Cookie("a");
	a.put(answered);
}

function getAuth()
{
	Mojo.Log.info("getAuth()");
	this.controller=Mojo.Controller.stageController.activeScene();
	this.controller.showDialog({
		template: "Auth-request/Auth-request-scene",
		assistant: new CustomDialogAssistant(this)
	});
	Mojo.Log.info("Dialog closed");

}

function checkAuth()
{
	var login = new Mojo.Model.Cookie("s");
	var password=new Mojo.Model.Cookie("p");
	if (login.get()&&password.get())
		return true;
	else return false;
}


function parser(key, value){

	//Mojo.Log.error("key=",key,"value=",value);
	//Mojo.Log.info("ff=",ff);
	if (key == "body") {

		//links
		value=value.replace(/(\s|^)(https?:\/\/(?:www\.)?([^\/\s\n\"]+)\/?[^\s\n\"]*)/g,"$1<a href=\"$2\">$3</a>");
		// @username
		value=value.replace(/(\s|^)(@[\w-]+)/g,"$1<a href=#username:$2>$2</a>");
		// #thread
		value=value.replace(/(\s|^)(#\d{1,7}\/?\d{1,3})/g,"$1<a href=#thread:$2>$2</a>");
		// *Bold*
		value=value.replace(/(\s|^)\*([^\*\n<>]+)\*(\s|$)/g,"$1<b>$2</b>$3");
		// /italic/
		value=value.replace(/(\s|^)\/([^\/\n<>]+)\/(\s|$)/g,"$1<i>$2</i>$3");
		// _underline_
		value=value.replace(/(\s|^)\_([^\_\n<>]+)\_(\s|$)/g,"$1<u>$2</u>$3");
		// ~strike~
		value=value.replace(/(\s|^)\~([^\~\n<>]+)\~(\s|$)/g,"$1<s>$2</s>$3");
		//return
		value=value.replace(/\\n/g,"<br>");
		value=value.replace(/\n/g,"<br>");

		//Mobile sites.
		//lenta.ru
		value=value.replace(/\<a href=\"http:\/\/lenta.ru\//g,"<a href=\"http://pda.lenta.ru/");
		//livejournal
		value=value.replace(/\<a href=\"http:\/\/([^\.]+)\.livejournal\.com\/(\d+)\.html/g,"<a href=\"http://m.livejournal.com/read/user/$1/$2");

	}else if(key=="tags") {
		
		value=""+value;
		value=value.replace(/,/g," ");
	}
	return value;

}


function getData(p)
{	
	this.controller=Mojo.Controller.stageController.activeScene();
	var list=this.controller.get('mainlistid');
	var spin=this.controller.get('spinnerid');
	if(spin)
	{
		spin.mojo.start();
		spin.style.visible="block";
	}
	var type=this.controller.sceneName;
	Mojo.Log.info("SceneName=",type);
	var xmlhttp = new XMLHttpRequest();
	Mojo.Log.info("open connection");
	var request="localhost";
	if (type == "Main") {
		if (p.list == "last") {
			if (p.more) {
				request = 'http://api.juick.com/messages?before_mid=' + p.lastthread;
				Mojo.Log.info("lastthread=", p.lastthread);
			}
			else {
				request = 'http://api.juick.com/messages?1=1';
				p.lastthread = 0;
			}
		}
		else if(p.list=="home"){
			if (p.more) {
				request = 'http://api.juick.com/home?before_mid=' + p.lastthread;
				Mojo.Log.info("lastthread=", p.lastthread);
			}
			else {
				request = 'http://api.juick.com/home';
				p.lastthread = 0;
			}
		}
	}
	else if(type=="Post"){
		request='http://api.juick.com/thread?mid='+p.thread;
		Mojo.Log.info("get thread=", p.thread);
	}
	else if(type=="User"){
		if(p.more)
			request='http://api.juick.com/messages?user_id='+p.userid+"&before_mid="+p.lastthread;
		else
			request='http://api.juick.com/messages?user_id='+p.userid;
	}
	xmlhttp.open('GET', request, true);
	Mojo.Log.info("Request="+request);

	if (checkAuth()) { //for home list
		var login = new Mojo.Model.Cookie("s");
		var password=new Mojo.Model.Cookie("p");
		var np=login.get()+":"+password.get();
		var auth=Base64.encode(np);
		xmlhttp.setRequestHeader("Authorization", "Basic " + auth);
	}

	xmlhttp.onreadystatechange = function(){
		//Mojo.Log.error("state change");
		if (xmlhttp.readyState == 4) {
			Mojo.Log.info("readystate=4");
			if (xmlhttp.status == 200) {
				Mojo.Log.info("status=200");
				var t=xmlhttp.responseText;
				t=t.replace(/\</g,"&lt;");
				t=t.replace(/\>/g,"&gt;");
				t=t.replace(/\t/g," ");
				var myData=JSON.parse(t,parser);
				var timezoneoffset=new Date().getTimezoneOffset()*60000;
				if (type == "Main") {
					var login = new Mojo.Model.Cookie("s");
					var uname=login.get();
					var a = new Mojo.Model.Cookie("a");
					if (a.get())
						answered=a.get();
					for(var i=0; i<myData.length;i++){
						if(answered)
						{
							for (j=0;j<answered.length;j++)
							{
								if(answered[j].thread==myData[i].mid)
								{
									myData[i].styleclass="withme"; //mark bookmark messages
									break;
								}
							}
						}
						//Date routine
						var date=new Date(myData[i].timestamp);
						date.setTime(date.getTime()-timezoneoffset*2);
						var d=new Array();
						d[0]=date.getUTCHours();
						d[1]=date.getMinutes();
						d[2]=date.getDate();
						d[3]=date.getMonth()+1;
						for(j=0;j<d.length;j++)
						{
							if(d[j]<10)d[j]="0"+d[j];
						}
						
						myData[i].mytimestamp=d[0]+":"+d[1]+" "+d[2]+"."+d[3];
						
						if(myData[i].user.uname.toLowerCase()==uname.toLowerCase())
						{
							myData[i].styleclass="myself"; //mark myself messages
						}
						if(myData[i].photo)
						{
							myData[i].imagelink="<a href="+myData[i].photo.medium+"><img width=100% src="+
								myData[i].photo.small+"></a>";
						}
						if(myData[i].video)
						{
							myData[i].videolink="<a href="+myData[i].video.mp4+">[VIDEO]</a></br>";
						}
					}
					p.lastthread=myData[myData.length-1].mid;
					if (p.more) {
						var l = list.mojo.getLength();
						Mojo.Log.info("list length=", l);
						p.messages = p.messages.concat(myData);
						Mojo.Log.info("messages length=", p.messages.length);
						list.mojo.setLength(0);
						list.mojo.noticeUpdatedItems(0,p.messages);
						list.mojo.revealItem(l, true);
						p.more = 0;
					}
					else {
						p.messages=myData;
						list.mojo.setLength(0);
						list.mojo.noticeUpdatedItems(0, p.messages);
					}
				}
				else if(type=="Post")
				{
					Mojo.Log.info("post list updated");
					myData[0].styleclass="firstmessage";
					var login = new Mojo.Model.Cookie("s");
					var uname=login.get();
					for(var i=0; i<myData.length;i++){
						if(myData[i].user.uname.toLowerCase()==uname.toLowerCase())
						{
							myData[i].styleclass="myself";
						}
						var date=new Date(myData[i].timestamp);
						date.setTime(date.getTime()-timezoneoffset*2);
						var d=new Array();
						d[0]=date.getUTCHours();
						d[1]=date.getMinutes();
						d[2]=date.getDate();
						d[3]=date.getMonth()+1;
						for(j=0;j<d.length;j++)
						{
							if(d[j]<10)d[j]="0"+d[j];
						}
						
						myData[i].mytimestamp=d[0]+":"+d[1]+" "+d[2]+"."+d[3];
						if(myData[i].photo)
						{
							myData[i].imagelink="<a href="+myData[i].photo.medium+"><img width=100% src="+
								myData[i].photo.small+"></a>";
						}
						if(myData[i].video)
						{
							myData[i].videolink="<a href="+myData[i].video.mp4+">[VIDEO]</a></br>";
						}
					}
					list.mojo.noticeUpdatedItems(0, myData);
					this.controller=Mojo.Controller.stageController.activeScene();
					p.username=myData[0].user.uname;
					p.userid=myData[0].user.uid;
					
					if(this.controller.sceneName=="Post")
						this.controller.get('headertext').update(p.username);
				} else if(type=="User")
				{
					p.lastthread=myData[myData.length-1].mid;
					for(i=0;i<myData.length;i++)
					{
						var date=new Date(myData[i].timestamp);
						date.setTime(date.getTime()-timezoneoffset*2);
						var d=new Array();
						d[0]=date.getUTCHours();
						d[1]=date.getMinutes();
						d[2]=date.getDate();
						d[3]=date.getMonth()+1;
						for(j=0;j<d.length;j++)
						{
							if(d[j]<10)d[j]="0"+d[j];
						}
						myData[i].mytimestamp=d[0]+":"+d[1]+" "+d[2]+"."+d[3];
						if(myData[i].photo)
						{
							myData[i].imagelink="<a href="+myData[i].photo.medium+"><img width=100% src="+
								myData[i].photo.small+"></a>";
						}
						if(myData[i].video)
						{
							myData[i].videolink="<a href="+myData[i].video.mp4+">[VIDEO]</a></br>";
						}
					}
					if(p.more)
					{
						var l = list.mojo.getLength();
						Mojo.Log.info("list length=", l);
						p.messages = p.messages.concat(myData);
						Mojo.Log.info("messages length=", p.messages.length);
						list.mojo.setLength(0);
						list.mojo.noticeUpdatedItems(0,p.messages);
						list.mojo.revealItem(l, true);
						p.more=0;
					}
					else
					{
						p.messages=myData;
						list.mojo.noticeUpdatedItems(0, myData);
					}
				}
				if(spin)
				{
					spin.mojo.stop();
					spin.style.visible = "none";
				}
			}
			else {
				switch(xmlhttp.status)
				{
					case 0:
						Mojo.Controller.errorDialog("Невозможно подключиться к сервру");
					break;
					case 403:
						Mojo.Controller.errorDialog("Forbidden<br>Неверный логин или пароль"+xmlhttp.statusText);
					break;
					case 404:
						Mojo.Controller.errorDialog("Not found<br>Запись не найдена, возможно она была удалена пользователем"+xmlhttp.statusText);
					break;
					default:
						Mojo.Controller.errorDialog(xmlhttp.status+"<br>"+xmlhttp.statusText);
					break;
				}
				if(spin)
				{
					spin.mojo.stop();
					spin.style.visible = "none";
				}

			}
		}
	}
	xmlhttp.send();
}

uploadSuccess=function(resp)
{
	newscene.attach="";
	Mojo.Log.info('Success : ' + Object.toJSON(resp));
	Mojo.Log.info('server returns', resp.httpCode);
	this.controller=Mojo.Controller.stageController.activeScene();
	if(this.controller.sceneName=="New")
	{
		var div=this.controller.get("imgdiv");
		var spin=this.controller.get('spinnerid');
		if(div)
		{
			div.style.display="none";
			spin.style.visible="none";
			spin.mojo.stop();
		}
		newscene.commandMenuModel.items[1].disabled=false;
		Mojo.Controller.stageController.popScene(this.controller, this);
	}
	if(resp.completed)
	{
		if(resp.httpCode==200)
		{
		Mojo.Controller.getAppController().showBanner("File uploaded",
				{source: 'notification'});
			if (newscene.thread)
			{
				addAnswered(newscene.thread);
				newscene.thread=0;
			}
		}
		else
		{
			Mojo.Controller.errorDialog(resp.httpCode)
		}
		newscene.commandMenuModel.items[1].disabled=false;
		newscene.uploadrequest.cancel();
	}
}

StageAssistant.prototype.handleCommand= function(event) {
	this.controller=Mojo.Controller.stageController.activeScene();
	var type=this.controller.sceneName;
	//Mojo.Log.info("controller=",Object.toJSON(this.controller));
	var p=this.controller.assistant;
    if (event.type == Mojo.Event.command) {
        switch (event.command) {
            case "do-New":
				Mojo.Controller.stageController.pushScene("New", {thread:0,replyid:0});
			break;
			case "do-Refresh":
				Mojo.Log.info("do-Refresh");
				if((!p.more) && p.messages && (type=="Main"))
				{
					
					p.messages.clear();
					this.controller.get("mainlistid").mojo.revealItem(0,true);
				}
				getData(p);
			break;
	        case "do-Send":
				Mojo.Log.info("Send button pressed");
				var tt=this.controller.get("newtext");
				var spin=this.controller.get('spinnerid');
				spin.style.visible="block";
				spin.mojo.start();
				var np="";
				var login = new Mojo.Model.Cookie("s");
				var password=new Mojo.Model.Cookie("p");
				if(login.get()&&password.get())
				{
					np=login.get()+":"+password.get();
				}
				else{
					getAuth();
					break;
				}
				var auth=Base64.encode(np);
				var end = "\r\n";
				var twoHyphens = "--";
				var boundary = "****+++++******+++++++********";
				var txt="";
				if(this.controller.sceneName=="New"){
					txt=tt.mojo.getValue();
					newscene.commandMenuModel.items[1].disabled=true;
					this.controller.modelChanged(newscene.commandMenuModel); 
				}
				else if(this.controller.sceneName=="Post")
				{
					txt="! #"+p.thread;
					Mojo.Log.info("post "+p.thread+" recommended");
					addAnswered(p.username,p.thread);
				}
				else if(this.controller.sceneName=="User")
				{
					txt="S @"+p.username;
					Mojo.Log.info("Subscribed to @"+p.username);
				}
				if(txt.length<2)return;
				if(newscene.attach.length>0) // sending picture or video
				{
					newscene.uploadrequest = new Mojo.Service.Request('palm://com.palm.downloadmanager/', {
						method: 'upload',
						parameters:
						{
							'fileName': newscene.attach,
							'url': 'http://'+np+'@api.juick.com/post',
							'fileLabel' : 'attach',
							'contentType': newscene.attachtype,
							subscribe: true,
							postParameters: [
								{
									key:"place_id",
									data:0,
									contentType:"multipart/form-data"
								},
								{
									key:"referer",
									data:"juick.com",
									contentType:"multipart/form-data",
								},
								{
									key:"body",
									data:txt,
									contentType:"multipart/form-data"
								}
								]
						},
						onSuccess : uploadSuccess.bind(this),
						onFailure : function (e){
							Mojo.Log.info('Failure : ' + Object.toJSON(e));
							spin.style.visible="none";
							spin.mojo.stop();
							Mojo.Controller.errorDialog(e.errorCode);
							newscene.commandMenuModel.items[1].disabled=false;
							this.controller=Mojo.Controller.stageController.activeScene();
							this.controller.modelChanged(newscene.commandMenuModel); 
						}.bind(this)
					});
					Mojo.Controller.getAppController().showBanner("Uploading...",{source: 'notification'});
					break;
				}
				var outStr = boundary+end+"Content-Disposition: form-data; name=\"place_id\"" + end + end + "0" + end;
				outStr += boundary+end+"Content-Disposition: form-data; name=\"referer\"" + end + end + "juick.com" + end;
				outStr += boundary+end+"Content-Disposition: form-data; name=\"body\"" + end + end + txt + end;
				outStr += boundary + twoHyphens + end;
				var xmlhttp = new XMLHttpRequest();
				if (xmlhttp) {
					xmlhttp.open('POST', 'http://api.juick.com/post', true);
					xmlhttp.setRequestHeader("Connection", "keep-alive");
					xmlhttp.setRequestHeader("Authorization", "Basic " + auth);
					xmlhttp.setRequestHeader("Charset", "UTF-8");
					xmlhttp.setRequestHeader("Content-Type", "multipart/form-data; charset=UTF-8");
					Mojo.Log.info("open connection");
					xmlhttp.onreadystatechange = function(){
						//Mojo.Log.error("state change");
						this.controller=Mojo.Controller.stageController.activeScene();
						if (xmlhttp.readyState == 4) {
							if (xmlhttp.status == 200) {
								Mojo.Log.info("Success:",xmlhttp.responseText);
								spin.style.visible="none";
								spin.mojo.stop();
								newscene.commandMenuModel.items[1].disabled=false;
								this.controller.modelChanged(newscene.commandMenuModel); 
								if (newscene.thread)
								{
									addAnswered(newscene.user,newscene.thread);
									newscene.thread=0;
									newscene.user="";
								}
								Mojo.Controller.stageController.popScene(this.controller, this);
							}
							else{
								Mojo.Log.error("Fail:",xmlhttp.responseText);
								spin.style.visible="none";
								spin.mojo.stop();
								newscene.commandMenuModel.items[1].disabled=false;
								this.controller.modelChanged(newscene.commandMenuModel); 
								switch(xmlhttp.status)
								{
									case 0:
										Mojo.Controller.errorDialog("Невозможно подключиться к серверу");
									break;
									case 403:
										Mojo.Controller.errorDialog("Forbidden<br>Неверный логин или пароль"+xmlhttp.statusText);
									break;
									default:
										Mojo.Controller.errorDialog(xmlhttp.status+"<br>"+xmlhttp.statusText);
									break;
								}
							}
						}
					}
					xmlhttp.send(outStr);
				}
				break;
				case "do-Prefs":
					getAuth();
				break;
			case 'do-Home':
				if (p.list == "last") {
					p.list = "home";
					this.controller.get("headertext").update("Моя лента");
					this.controller.get("mainlistid").mojo.revealItem(0,true);
					if(p.messages)
						p.messages.clear();
					p.more=0;
					p.lastthread=0;
					getData(p);
				}
			break;
			case 'do-Last':
				if (p.list == "home") {
					p.list = "last";
					this.controller.get("headertext").update("Последние сообщения");
					this.controller.get("mainlistid").mojo.revealItem(0,true);
					if(p.messages)
						p.messages.clear();
					p.more=0;
					p.lastthread=0;
					getData(p);
				}
			break;
				
				
			case "do-Attach":
				var params = {
				actionType: 'attach',
				kinds: ['image','video'],
				onSelect: function(file){
					Mojo.Log.info("picked file",newscene.attach);
					if(!(file.fullPath.match(/.jpg$/i)||file.fullPath.match(/.mp4$/i))){
						Mojo.Controller.errorDialog("Принимаются только фотографии формата jpg и видео mp4");
						return;
					}
					newscene.attach = file.fullPath;
					this.controller=Mojo.Controller.stageController.activeScene();
					var img=this.controller.get("img");
					if(file.fullPath.match(/.jpg$/i))
					{
						img.src=file.fullPath;	
						newscene.attachtype="img";
					}
					else
					{
						img.src=file.iconPath;
						newscene.attachtype="video";
					}
					img.parentNode.style.display="block";
					img.style.width="50%";
					img.style.height="75%";
						
					}

				}
			Mojo.FilePicker.pickFile(params, this.controller.stageController);
			break;
			case "do-About":
				Mojo.Controller.stageController.pushScene("About");
			break;
			case "do-Bookmarks":
				Mojo.Controller.stageController.pushScene("Bookmarks");
			break;
			case "do-ClearBookmarks":
				answered.clear();
				var a=new Mojo.Model.Cookie("a");
				a.put(answered);
				this.controller=Mojo.Controller.stageController.activeScene();
				Mojo.Controller.stageController.popScene(this.controller.sceneName);
			break;
			case "do-AddBookmark":
				addAnswered(p.username,p.thread);
			break;
			default:
				break;

        }
    }
    else if(event.type==Mojo.Event.commandEnable)
    {
		Mojo.Log.info("commandEnable");
	}
}
